package com.emagic.manage.utils;


import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SpecialCharactersInputFilter implements InputFilter {

    private Pattern pattern;

    public SpecialCharactersInputFilter() {
        this.pattern = Pattern.compile("^[a-zA-Z0-9\\u4e00-\\u9fa5]+");
    }

    public SpecialCharactersInputFilter(String pattern) {
        this.pattern = Pattern.compile(pattern);
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        String sourceText = source.toString();

        //验证删除等按键
        if (TextUtils.isEmpty(source)) {
            return "";
        }
        Matcher matcher = pattern.matcher(source);
        if (!matcher.matches()) {
            return "";
        }
        return dest.subSequence(dstart, dend) + sourceText;
    }
}
